package com.qf.upload;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUpload {
    public static String fileUpload(MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return null;
        }
        // 获取应用的根目录
        Path rootPath = Paths.get(new ApplicationHome(FileUpload.class).getSource().getParent()).toAbsolutePath().normalize();
        Path uploadPath = rootPath.resolve("upload");
        // 确保上传目录存在
        if (!Files.exists(uploadPath)) {
            try {
                Files.createDirectories(uploadPath);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        // 获取文件名，避免路径遍历攻击
        String originalFilename = multipartFile.getOriginalFilename();
        if (StringUtils.hasText(originalFilename) && originalFilename.contains("..")) {
            // 如果文件名包含路径分隔符（如..），则视为不安全并拒绝上传
            return null;
        }
        String safeFilename = sanitizeFilename(originalFilename);
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String finalFilename = timestamp + "_" + safeFilename;
        Path targetFile = uploadPath.resolve(finalFilename);
        try (FileOutputStream fos = new FileOutputStream(targetFile.toFile())) {
            fos.write(multipartFile.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return targetFile.toString();
    }

    //将不在指定字符集内的字符替换为下划线，防止出现安全隐患
    private static String sanitizeFilename(String filename) {
        return filename.replaceAll("[^a-zA-Z0-9._-]", "_");
    }
}
